package com.jr.controller;

import com.google.gson.Gson;
import com.jr.service.IUserService;
import com.jr.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@WebServlet("/login/*")
public class UserController extends HttpServlet {
    private IUserService ius = new UserServiceImpl();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String requestURI = request.getRequestURI();

        // 找到最后一个"/"的位置并加1，得到方法名的起始位置
        int index = requestURI.lastIndexOf("/") + 1;

        // 从URI中提取方法名，例如：queryByPid
        String mName = requestURI.substring(index);

        // 获取当前类的Class对象
        Class cla = this.getClass();
        Method method = null;
        try {
            // 通过反射获取指定方法名的Method对象
            // 该方法需要接受HttpServletRequest和HttpServletResponse两个参数
            method = cla.getMethod(mName, HttpServletRequest.class, HttpServletResponse.class);
            response.setContentType("application/json;charset=utf-8");
            request.setCharacterEncoding("utf-8");
            // 使用反射调用获取到的方法，传入当前对象和请求、响应参数
            method.invoke(this, request, response);
        } catch (NoSuchMethodException e) {
            // 如果找不到对应的方法，打印异常堆栈
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // 如果方法不可访问，打印异常堆栈
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // 如果方法调用抛出异常，打印异常堆栈
            e.printStackTrace();
        }
    }

    public void userlogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String account = request.getParameter("account");
        String password = request.getParameter("password");
        boolean login = ius.login(account, password);
        if(login){
            request.getSession().setAttribute("login",account);
            response.getWriter().println(new Gson().toJson("登录成功！"));
        }else{
            response.getWriter().println(new Gson().toJson("登录失败，账号或密码错误"));
        }



    }
}
